<template>
  <div class="roles">
      <el-button type="primary" plain @click="addVisible=true">添加角色</el-button>
      <el-table border class="mt-15" :data="roleList" style="width: 100%">
            <el-table-column type="expand">
                <template slot-scope="scope">
                    <el-row v-for="firstC in scope.row.children" :key="firstC.id">
                        <el-col :span="4">
                            <el-tag closable @close="deleteRight(scope.row,firstC.id)">
                                {{firstC.authName}}
                            </el-tag>
                            <i class="el-icon-arrow-right" v-if="firstC.children.length !==0"></i>
                        </el-col>
                        <el-col :span="20">
                            <el-row v-for="secondC in firstC.children" :key="secondC.id">
                                <el-col :span="5">
                                    <el-tag closable type="success" @close="deleteRight(scope.row,secondC.id)">{{secondC.authName}}</el-tag>
                                    <i class="el-icon-arrow-right" v-if="secondC.children.length !==0"></i>
                                </el-col>
                                <el-col :span="19">
                                    <el-tag closable @close="deleteRight(scope.row,thirdC.id)" type="warning" v-for="thirdC in secondC.children" :key="thirdC.id">
                                        {{thirdC.authName}}
                                    </el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                    <el-row v-if="scope.row.children.length === 0">
                        <el-col :span="24">该角色没有分配权限,请前往分配</el-col>
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column label="#" type="index" width="50px"></el-table-column>
            <el-table-column label="角色名称" prop="roleName" width="170px"></el-table-column>
            <el-table-column label="描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作" width="250px">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" plain icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>
                    <el-button size="mini" type="danger" plain icon="el-icon-delete" @click="detRoles(scope.row)"></el-button>
                    <el-button size="mini" type="warning" @click="showDialog(scope.row)" plain icon="el-icon-check" title="授权角色"></el-button>
                </template>
            </el-table-column>
      </el-table>
      <!-- 授权角色对话框 -->
      <el-dialog title="授权角色" :visible.sync = "dialogVisible">
          <div class="tree-container">
              <el-tree :data="rightList" show-checkbox ref="tree"
              node-key="id" :default-expand-all="true" 
              :default-checked-keys="selectedRights" :props="defaultProps">
              </el-tree>
          </div>
          <div slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitGrant()">确认</el-button>
          </div>
      </el-dialog>
      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色" :visible.sync = "addVisible">
            <el-form :model="addForm" lable-width="80px" :rules="rules" ref="addRoleForm">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addVisible=false">取消</el-button>
                <el-button type="primary" @click="addRoleSubmit('addRoleForm')">确认</el-button>
            </div>
      </el-dialog>
      <!-- 编辑角色对话框 -->
      <el-dialog title="编辑角色" :visible.sync = "editVisible">
            <el-form :model="editForm" lable-width="80px" :rules="rules" ref="editRoleForm">
                <el-form-item label="角色id" prop="roleId">
                    <el-input v-model="editForm.roleId" auto-complete="off" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editForm.roleDesc" auto-complete="off"></el-input>
                </el-form-item>
             </el-form>    
            <div slot="footer" class="dialog-footer">
                <el-button @click="editVisible=false">取消</el-button>
                <el-button type="primary" @click="editRoleSubmit('editRoleForm')">确认</el-button>
            </div>
      </el-dialog>
  </div>
</template>

<script>
import {getRoleList,deleteRoleRight,getRightList,grandRoleRight,addRole,deleteRole,getRoleById,editRole} from '@/api/index'

export default {
    data () {
        return {
            roleList: [],
            rightList:[],//权限列表
            dialogVisible:false,
            addVisible:false,
            editVisible:false,
            defaultProps:{
                children:'children',
                label:'authName'
            },
            addForm:{
                roleName:'',
                roleDesc:''
            },
            editForm:{
                roleName:'',
                roleDesc:'',
                roleId:0
            },
            selectedRights: [], // 保存默认选中的权限id
            currentRole: {}, // 保存点击的角色
            rules:{
                roleName:[{
                    required:true,message:'请输入角色名',trigger:'blur'
                }],
                roleDesc:[{
                    required:true,message:'请输入描述',trigger:'blur'
                }],
            },
        }
    },
    created () {
        this.initList()
    },
    methods:{
        //获取数据
        async initList () {
            let {meta,data} = await getRoleList()
            if(meta.status === 200) return this.roleList=data
        },
        //删除权限
        async deleteRight (row,rightId) {
            let flog = await this.$confirm("是否确定删除权限",{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(()=>{})
            if(!flog) return this.$message.info({message:'取消删除'})
            let {meta,data} = await deleteRoleRight({roleId:row.id,rightId})
            if(meta.status !==200) return this.$message.error({message:meta.msg})
            this.$message.success({message:meta.msg})
            row.children = data
        },
        //显示授权角色模态框
        async showDialog (row) {
            this.dialogVisible = true
            this.currentRole = row
            let {meta,data} = await getRightList({type:'tree'})
            if (meta.status != 200) return this.$message.error({message:meta.msg})
            console.log(data);
            this.rightList = data
            //遍历之前让数组清空
            this.selectedRights.length = 0
            // 取出当前点击角色的所有权限， 然后遍历到取出它里面的所有的项的id，存进selectedRights中
            // 1. 遍历第一个children取出一级权限
            this.currentRole.children.forEach(first=>{
                if(first.children&&first.children.length !==0){
                    //2. 遍历取出二级权限
                    first.children.forEach(second=>{
                        if(second.children&&second.children.length !==0){
                            //3. 遍历取出三级权限
                            second.children.forEach(third=>{
                                this.selectedRights.push(third.id)
                            })
                        }
                    })
                }
            })
        },
        //提交授权
        async submitGrant(){
            // 获取到所有选中的权限ID
            let rids = this.$refs.tree.getCheckedKeys().join(',')
            console.log(rids);
            let {meta,data} = await grandRoleRight({roleId:this.currentRole.id,rids})
            if(meta.status !== 200) return this.$message.error({message:meta.msg})
            this.$message.success({message:meta.msg})
            this.dialogVisible = false
            this.initList()
        },
        //提交添加
        async addRoleSubmit(formName){
            this.$refs[formName].validate(valide =>{
                if(valide){
                    addRole(this.addForm).then(res=>{
                        console.log(res);
                        if (res.meta.status!==201) return this.$message.error({message:res.meta.msg})
                        this.$message.success({message:res.meta.msg})
                        this.addVisible = false
                        this.initList()
                    })
                }
            })
        },
        //删除角色
        async detRoles(row){
            let flog = await this.$confirm('此操作将永久删除该角色，是否确定?','提示',{
                confirmButtonText:'确定',
                cancelButtonText:'取消',
                type:'warning'
            }).catch(()=>{})
            if(!flog) return this.$message.info({message:'已取消删除'}) 
            let {meta,data} = await deleteRole(row.id)
            if(meta.status!==200) return this.$message.error({message:meta.msg})
            this.$message.success({message:meta.msg})
            this.initList()
        },
        //通过id获取角色信息
        async showEditDialog(row){
            this.editVisible = true
            let {meta,data} = await getRoleById(row.id)
            if(meta.status !== 200) return this.$message.error({message:meta.msg})
            this.editForm.roleId=data.roleId
            this.editForm.roleName=data.roleName
            this.editForm.roleDesc=data.roleDesc
        },
        //编辑角色
        async editRoleSubmit(formName){
            console.log(formName);
            this.$refs[formName].validate(valide=>{
                if(valide)[
                    editRole(this.editForm).then(res=>{
                        console.log(res.data);
                        if(res.meta.status!==200) return this.$message.error({message:res.meta.msg})
                        this.$message.success({message:res.meta.msg})
                        this.editVisible = false
                        this.initList()
                    })
                ]
            })
        }
    }
}
</script>

<style lang="less" scoped>
    .roles {
        .el-tag{
            margin-right: 5px;
            margin-bottom: 5px;
        }
        .tree-container{
            height: 300px;
            overflow: auto;
        }
    }
</style>